package com.example.exception;

import com.example.message.MessageSourceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;
@ControllerAdvice
public class BaseExceptionHandleAction {
    @Autowired
    private MessageSourceService sourceService;

    @Autowired
    private MessageSource messageSource;
    /** 基于@ExceptionHandler异常处理 */
    @ExceptionHandler
    @ResponseBody
    public Map<String, Object>  handleAndReturnData(HttpServletRequest request,
                                                    HttpServletResponse response, Exception ex) {
        ex.printStackTrace();
        Map<String, Object> data = new HashMap<String, Object>();
        if(ex instanceof MultipartException) {
            MultipartException e = (MultipartException)ex;
            data.put("code", "1120");
            data.put("msg", messageSource.getMessage("1120",(Object[])null, LocaleContextHolder.getLocale()));
        }
        if(ex instanceof ServiceException) {
            ServiceException e = (ServiceException)ex;
            data.put("code", e.getCode());
            data.put("msg", messageSource.getMessage(e.getCode(),(Object[])null, LocaleContextHolder.getLocale()));
        }
        data.put("code", "500");
        data.put("data", ex.toString());
        //data.put("exeception",ex.toString());
        return data;
    }
}
